package com.example.controller;

    import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
@CrossOrigin(origins = "*")
public class UploadController {

    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;

    @Value("${minio.imageDomain}")
    private String imageDomain;

    @PostMapping("/faceImage")
    public Map<String, Object> uploadFaceImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "fileName", required = false) String fileName,
            @RequestParam(value = "bucketName", required = false) String customBucketName) {
        
        Map<String, Object> result = new HashMap<>();
        
        if (file.isEmpty()) {
            result.put("code", 400);
            result.put("message", "文件为空");
            return result;
        }
        
        try {
            // 使用自定义bucket名称或默认名称
            String targetBucket = customBucketName != null ? customBucketName : bucketName;
            
            // 确保bucket存在
            if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(targetBucket).build())) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(targetBucket).build());
                logger.info("创建MinIO桶: {}", targetBucket);
            }

            // 生成文件名
            if (fileName == null || fileName.isEmpty()) {
                String originalFilename = file.getOriginalFilename();
                String extension = originalFilename != null ? 
                    originalFilename.substring(originalFilename.lastIndexOf(".")) : ".jpg";
                fileName = "face_" + System.currentTimeMillis() + "_" + UUID.randomUUID().toString().substring(0, 8) + extension;
            }

            // 上传文件到MinIO
            minioClient.putObject(
                PutObjectArgs.builder()
                    .bucket(targetBucket)
                    .object(fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build()
            );

            // 构建完整的图片访问URL
            String imageUrl = imageDomain + "/" + targetBucket + "/" + fileName;
            
            result.put("code", 200);
            result.put("message", "上传成功");
            Map<String, String> data = new HashMap<>();
            data.put("fileName", fileName);
            data.put("imageUrl", imageUrl);
            result.put("data", data);
            
            logger.info("图片上传成功: {}", imageUrl);

        } catch (Exception e) {
            logger.error("图片上传失败: {}", e.getMessage(), e);
            result.put("code", 500);
            result.put("message", "上传失败: " + e.getMessage());
        }

        return result;
    }

    @PostMapping("/tongueImage")
    public Map<String, Object> uploadTongueImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "fileName", required = false) String fileName,
            @RequestParam(value = "bucketName", required = false) String customBucketName) {
        
        Map<String, Object> result = new HashMap<>();
        
        if (file.isEmpty()) {
            result.put("code", 400);
            result.put("message", "文件为空");
            return result;
        }
        
        try {
            // 使用自定义bucket名称或默认名称
            String targetBucket = customBucketName != null ? customBucketName : bucketName;
            
            // 确保bucket存在
            if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(targetBucket).build())) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(targetBucket).build());
                logger.info("创建MinIO桶: {}", targetBucket);
            }

            // 生成文件名
            if (fileName == null || fileName.isEmpty()) {
                String originalFilename = file.getOriginalFilename();
                String extension = originalFilename != null ? 
                    originalFilename.substring(originalFilename.lastIndexOf(".")) : ".jpg";
                fileName = "tongue_" + System.currentTimeMillis() + "_" + UUID.randomUUID().toString().substring(0, 8) + extension;
            }

            // 上传文件到MinIO
            minioClient.putObject(
                PutObjectArgs.builder()
                    .bucket(targetBucket)
                    .object(fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build()
            );

            // 构建完整的图片访问URL
            String imageUrl = imageDomain + "/" + targetBucket + "/" + fileName;
            
            result.put("code", 200);
            result.put("message", "上传成功");
            Map<String, String> data = new HashMap<>();
            data.put("fileName", fileName);
            data.put("imageUrl", imageUrl);
            result.put("data", data);
            
            logger.info("舌部图片上传成功: {}", imageUrl);

        } catch (Exception e) {
            logger.error("舌部图片上传失败: {}", e.getMessage(), e);
            result.put("code", 500);
            result.put("message", "上传失败: " + e.getMessage());
        }

        return result;
    }

    @GetMapping("/health")
    public Map<String, Object> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "服务正常");
        result.put("timestamp", System.currentTimeMillis());
        return result;
    }
}
